<?php
include_once 'modules/Pay.php';

// 管理员
class AdminAction extends BaseAction {
  /**
   * 管理员登录
   * @return ajaxObject
   */
  public function login() {
    $username = $this->request['userName'];
    $password = $this->request['password'];
    $openId = $this->request['openId'];
    $UserData = parent::_modelDetail("Admin", "admin_username", $username);

    if ($UserData) {
        $salt = $UserData['admin_salt'];
        $postPassword = Tools::getPassword($password, $salt);

        if ($UserData['admin_password'] == $postPassword) {
            // TODO: 暂时没有UserView，所以删除密码和盐字段即可
            unset($UserData['admin_salt']);
            unset($UserData['admin_password']);

            // 存储session
            session('trackUser', $UserData);

            if ($openId) {
              $Bind = M("Bind");
              $bindCon['bind_admin_id'] = $UserData['admin_id'];
              $bindCon['bind_user_openid'] = $openId;
              $bindExists = $Bind->where($bindCon)->find();

              if(!$bindExists) {
                $Bind->add($bindCon);
              }
            }

            $this->ajaxReturn($UserData, '登录成功', 'ok');
        }
    }

    $this->ajaxReturn(trace(), '用户名或密码错误', 'error');
  }

  public function currentUser() {
    $trackUser = session('trackUser');

    if($trackUser) {
      $id = $trackUser['admin_id'];
      $result = M('Admin')->field('admin_id, admin_username, admin_nickname, admin_created')->find($id);
      if($result) {
        $ret['name'] = $result['admin_username'];
        $ret['avatar'] = 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
        $ret['userid'] = $result['admin_id'];

        $con['notice_admin_id'] = $id;
        $con['notice_is_read'] = 0;
        $ret['notifyCount'] = M('Notice')->where($con)->count();
        $this->ajaxReturn($ret, 'success', 1);
      }
    }

    $this->ajaxReturn(trace(), '用户信息不存在', 0);
  }

  /**
   * 管理员登出
   * @return ajaxObject
   */
  public function logout() {
    session('trackUser', null);
    $this->ajaxReturn('', '已退出登录', 1);
  }

  /**
   * 创建管理员
   * @return ajaxObject
   */
  public function create() {
    $defaultPassword = '123456';
    $salt = Tools::getSalt();
    $this->request['admin_salt'] = $salt;
    $this->request['admin_password'] = Tools::getPassword($defaultPassword, $salt);
    parent::_modelAdd('Admin', '管理员');
  }

  /**
   * 删除管理员
   * @return ajaxObject
   */
  public function delete() {
    $result = parent::_modelDelete('Admin');
    if($result){
      $this->ajaxReturn('', '删除管理员成功', 1);
    }else {
      $this->ajaxReturn('', '删除管理员失败', 0);
    }
  }

  public function wechat() {
    $tools = new JsApiPay();
    $openId = $tools->GetOpenid();

    $url = 'https://'.$_SERVER['HTTP_HOST'].'/track/web/dist/index.html#/user/login?openid='.$openId;
    Header("Location: $url");
  }
}